/**
 * 学生成绩相关的mock数据
 */

import { faker } from '@faker-js/faker/locale/zh_CN'

// 当前时间
const now = new Date()

// 学科列表
const subjects = [
  { id: 1, name: '数学' },
  { id: 2, name: '语文' },
  { id: 3, name: '英语' },
  { id: 4, name: '物理' },
  { id: 5, name: '化学' },
  { id: 6, name: '生物' }
]

// 试卷总分，各类型最低分、通过分和最高分
const scoreRanges = {
  totalScore: 100,
  minScore: 40,
  passScore: 60,
  highScore: 90
}

// 题目类型
const questionTypes = {
  SINGLE_CHOICE: 1,
  MULTIPLE_CHOICE: 2,
  FILL_BLANK: 3,
  SHORT_ANSWER: 4
}

/**
 * 生成随机成绩
 * @param {Number} min 最低分
 * @param {Number} max 最高分
 * @returns {Number} 随机分数
 */
const generateRandomScore = (min, max, total) => {
  const score = Math.floor(Math.random() * (max - min + 1)) + min
  return Math.min(score, total)
}

/**
 * 生成成绩列表数据
 * @param {Object} params 查询参数
 * @returns {Object} 成绩列表数据
 */
export function mockScoreList(params = {}) {
  const { page = 1, limit = 10, subjectId = '', startTime = '', endTime = '' } = params
  
  // 生成随机的成绩记录数量（10-50条）
  const totalCount = Math.floor(Math.random() * 41) + 10
  
  // 计算分页数据
  const start = (page - 1) * limit
  const end = Math.min(start + limit, totalCount)
  
  // 生成成绩列表
  const list = []
  
  for (let i = 0; i < totalCount; i++) {
    // 如果不在当前页范围内，则跳过详细数据生成
    if (i < start || i >= end) {
      continue
    }
    
    // 随机选择一个学科
    const subject = subjectId 
      ? subjects.find(s => s.id === Number(subjectId)) 
      : subjects[Math.floor(Math.random() * subjects.length)]
    
    // 随机考试日期（过去3个月内）
    const examDate = faker.date.between({
      from: new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000),
      to: now
    })
    
    // 如果设置了日期范围，检查是否符合条件
    if (startTime && new Date(startTime) > examDate) {
      continue
    }
    if (endTime && new Date(endTime) < examDate) {
      continue
    }
    
    // 随机总人数 (30-200)
    const totalStudents = Math.floor(Math.random() * 171) + 30
    
    // 随机排名 (1-totalStudents)
    const rank = Math.floor(Math.random() * totalStudents) + 1
    
    // 生成随机成绩
    let score = null
    if (rank / totalStudents <= 0.1) {
      // 排名前10%，高分概率大
      score = generateRandomScore(scoreRanges.highScore, scoreRanges.totalScore, scoreRanges.totalScore)
    } else if (rank / totalStudents <= 0.6) {
      // 排名前60%，通过概率大
      score = generateRandomScore(scoreRanges.passScore, scoreRanges.highScore, scoreRanges.totalScore)
    } else {
      // 其他，低分概率大
      score = generateRandomScore(scoreRanges.minScore, scoreRanges.passScore, scoreRanges.totalScore)
    }
    
    // 确保即使是排名靠后的，也有一定概率获得及格分数
    if (Math.random() > 0.7) {
      score = Math.max(score, scoreRanges.passScore)
    }
    
    // 创建成绩记录
    list.push({
      id: i + 1,
      examinationName: `${subject.name}${faker.date.month()}月测试`,
      examTime: examDate.toISOString(),
      subjectId: subject.id,
      subjectName: subject.name,
      score,
      totalScore: scoreRanges.totalScore,
      rank,
      totalStudents
    })
  }
  
  return {
    list,
    total: totalCount
  }
}

/**
 * 生成随机选项内容
 * @returns {Object} 选项内容对象
 */
const generateOptions = () => {
  const options = {}
  const optionKeys = ['A', 'B', 'C', 'D']
  
  optionKeys.forEach(key => {
    options[key] = faker.lorem.sentence(3, 8)
  })
  
  return options
}

/**
 * 生成填空题答案
 * @returns {String} 答案
 */
const generateFillBlankAnswer = () => {
  return faker.lorem.words(1)
}

/**
 * 生成单选题答案
 * @returns {String} 答案选项
 */
const generateSingleChoiceAnswer = () => {
  const options = ['A', 'B', 'C', 'D']
  return options[Math.floor(Math.random() * options.length)]
}

/**
 * 生成多选题答案
 * @returns {String} 答案选项，如"A,B,D"
 */
const generateMultipleChoiceAnswer = () => {
  const options = ['A', 'B', 'C', 'D']
  const count = Math.floor(Math.random() * 3) + 1 // 1-3个选项
  
  // 随机排序并选取前count个
  const selected = [...options]
    .sort(() => Math.random() - 0.5)
    .slice(0, count)
    .sort() // 按字母排序
  
  return selected.join(',')
}

/**
 * 生成大题
 * @param {Number} index 大题序号
 * @param {Number} maxScore 大题最高分数
 * @returns {Object} 大题对象
 */
const generateBigQuestion = (index, maxScore) => {
  const questionTypes = [
    { id: 1, name: '单选题', score: 5 },
    { id: 2, name: '多选题', score: 5 },
    { id: 3, name: '填空题', score: 10 }
  ]
  
  // 选择题型
  const questionType = questionTypes[index % questionTypes.length]
  
  // 确定题目数量
  const count = Math.floor(maxScore / questionType.score)
  
  // 生成题目
  const questions = []
  
  for (let i = 0; i < count; i++) {
    const question = {
      id: index * 100 + i,
      name: faker.lorem.sentence(),
      score: questionType.score,
      questionTypeId: questionType.id,
      // 添加answerTypeId字段: 1表示主观题，2表示客观题
      answerTypeId: questionType.id === 3 ? 1 : 2
    }
    
    // 根据题型设置内容和答案
    if (questionType.id === 1) { // 单选题
      question.questionContent = JSON.stringify(generateOptions())
      question.answer = generateSingleChoiceAnswer()
      question.studentAnswer = Math.random() > 0.7 ? question.answer : generateSingleChoiceAnswer()
    } else if (questionType.id === 2) { // 多选题
      question.questionContent = JSON.stringify(generateOptions())
      question.answer = generateMultipleChoiceAnswer()
      question.studentAnswer = Math.random() > 0.7 ? question.answer : generateMultipleChoiceAnswer()
    } else { // 填空题
      question.questionContent = faker.lorem.paragraph()
      question.answer = generateFillBlankAnswer()
      question.studentAnswer = Math.random() > 0.7 ? question.answer : generateFillBlankAnswer()
      question.checkDetail = question.studentAnswer !== question.answer 
        ? '答案不完整，扣分' 
        : ''
    }
    
    // 计算得分
    if (question.studentAnswer === question.answer) {
      question.finalScore = question.score
    } else if (question.questionTypeId === 3) { // 填空题有部分得分可能
      question.finalScore = Math.random() > 0.5 ? Math.floor(question.score / 2) : 0
    } else {
      question.finalScore = 0
    }
    
    questions.push(question)
  }
  
  return {
    id: index,
    name: `${questionType.name}`,
    questions
  }
}

/**
 * 生成成绩详情数据
 * @param {Number} examId 考试ID
 * @returns {Object} 成绩详情数据
 */
export function mockScoreDetail(examId) {
  // 随机选择一个学科
  const subject = subjects[Math.floor(Math.random() * subjects.length)]
  
  // 随机考试日期（过去3个月内）
  const examDate = faker.date.between({
    from: new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000),
    to: now
  })
  
  // 随机总人数 (30-200)
  const totalStudents = Math.floor(Math.random() * 171) + 30
  
  // 随机排名 (1-totalStudents)
  const rank = Math.floor(Math.random() * totalStudents) + 1
  
  // 设置大题数量和分值分布
  const bigQuestionsConfig = [
    { score: 25 }, // 第一大题25分
    { score: 25 }, // 第二大题25分
    { score: 50 }  // 第三大题50分
  ]
  
  // 生成大题
  const bigQuestions = bigQuestionsConfig.map((config, index) => 
    generateBigQuestion(index, config.score)
  )
  
  // 计算总分和学生得分
  let totalScore = 0
  let score = 0
  
  bigQuestions.forEach(bigQuestion => {
    bigQuestion.questions.forEach(question => {
      totalScore += question.score
      score += question.finalScore
    })
  })
  
  // 确保分数合理
  if (rank / totalStudents <= 0.1) {
    // 前10%，分数不应低于总分的85%
    score = Math.max(score, Math.floor(totalScore * 0.85))
  } else if (rank / totalStudents <= 0.5) {
    // 前50%，分数不应低于60%
    score = Math.max(score, Math.floor(totalScore * 0.6))
  }
  
  // 限制在总分范围内
  score = Math.min(score, totalScore)
  
  return {
    id: examId,
    examinationName: `${subject.name}${faker.date.month()}月测试`,
    examTime: examDate.toISOString(),
    subjectId: subject.id,
    subjectName: subject.name,
    score,
    totalScore,
    rank,
    totalStudents,
    bigQuestions
  }
}

// 导出mock数据处理函数
export default {
  mockScoreList,
  mockScoreDetail
} 